package downloader

import (
	"context"
	"errors"
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"gitee.com/Luna-CY/hui-hui/internal/util/goroutine"
	"time"
)

// Retry 重试下载任务
func (cls *Downloader) Retry(id string) (*Task, error) {
	cls.mutex.RLock()
	defer cls.mutex.RUnlock()

	if cls.quit {
		return nil, errors.New("下载器已退出，无法下载任务")
	}

	if task, ok := cls.tasks[id]; ok {
		if TaskStateDownloading != task.State && TaskStateComplete != task.State {
			// 重新创建上下文
			task.ctx, task.cancel = context.WithCancel(context.Background())

			task.State = TaskStateDownloading
			task.Message = "下载中"
			task.StartTime = time.Now()
			task.DownloadSize = 0

			logger.GetLogger().Sugar().Infof("下载器: 重新下载文件开始: %s", task.RemoteAddress)
			goroutine.Go(func() {
				cls.started(task)
			})

			return task, nil
		}

		return nil, errors.New("该任务当前不可重试下载")
	}

	return nil, errors.New("任务ID不存在")
}
